#!/bin/bash

# 修复APScheduler依赖问题脚本

# 确保脚本在正确的目录执行
cd /usr/local/nginx/html/prod/dz || {
    echo "无法切换到应用目录，脚本退出"
    exit 1
}

# 检查虚拟环境是否激活
if [[ -z $VIRTUAL_ENV ]]; then
    echo "激活虚拟环境..."
    source /usr/local/nginx/html/prod/dz/venv/bin/activate
    if [[ -z $VIRTUAL_ENV ]]; then
        echo "虚拟环境激活失败，请检查虚拟环境路径是否正确"
        exit 1
    fi
    echo "虚拟环境激活成功: $VIRTUAL_ENV"
else
    echo "虚拟环境已激活: $VIRTUAL_ENV"
fi

# 检查requirements.txt文件是否存在
if [[ ! -f requirements.txt ]]; then
    echo "requirements.txt文件不存在，请检查文件路径"
    exit 1
fi

# 安装依赖（使用-r参数）
echo "安装项目依赖..."
pip install -r requirements.txt
if [[ $? -ne 0 ]]; then
    echo "依赖安装失败，请检查网络连接或requirements.txt内容"
    exit 1
fi

echo "依赖安装成功"

# 验证apscheduler是否安装成功
python -c "import apscheduler; print('APScheduler版本:', apscheduler.__version__)" || {
    echo "APScheduler安装验证失败，尝试手动安装..."
    pip install APScheduler~=3.10.4
    if [[ $? -ne 0 ]]; then
        echo "APScheduler手动安装失败"
        exit 1
    fi
    echo "APScheduler手动安装成功"
}

# 检查scheduler.py文件是否存在
if [[ ! -f app/scheduler.py ]]; then
    echo "scheduler.py文件不存在，创建文件..."
    cat > app/scheduler.py << EOF
from flask import current_app
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def configure_scheduler(app):
    """配置并返回后台调度器"""
    scheduler = BackgroundScheduler(app.config)
    scheduler.start()
    logger.info('调度器已启动')

    # 示例任务：每分钟执行一次
    @scheduler.scheduled_job('interval', minutes=1)
    def test_task():
        with app.app_context():
            logger.info(f'测试任务执行时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
            # 这里可以添加实际任务逻辑

    return scheduler
EOF
    echo "scheduler.py文件创建成功"
else
    echo "scheduler.py文件已存在"
fi

# 检查main.py文件是否存在
if [[ ! -f main.py ]]; then
    echo "main.py文件不存在，请检查文件路径"
    exit 1
fi

# 启动应用
read -p "是否启动应用? (y/n): " start_app
if [[ $start_app == 'y' || $start_app == 'Y' ]]; then
    echo "启动应用..."
    gunicorn -w 1 -b 0.0.0.0:9201 main:app
fi

echo "修复脚本执行完成"